<template>
  <div class="detail-wrap">
    <el-form :model="weiboDetailFrom" :rules="rules" ref="weiboDetailFrom" label-width="160px" label-position="left">
      <el-form-item :label="$t('config.channel.weiboName')" prop="name">
        <el-input size="mini" v-model.trim="weiboDetailFrom.name" auto-complete="off"></el-input>
      </el-form-item>
      <el-form-item :label="$t('config.channel.addWeiboId2')" prop="weiboId">
        <el-input size="mini" v-model.trim="weiboDetailFrom.weiboId" auto-complete="off"></el-input>
      </el-form-item>
      <el-form-item label="TOKEN" prop="access_token">
        <el-input size="mini" v-model.trim="weiboDetailFrom.access_token" auto-complete="off"></el-input>
      </el-form-item>
      <el-form-item label="URL" prop="appUrl">
        <el-input size="mini"  v-model.trim="weiboDetailFrom.appUrl" auto-complete="off" :disabled="true"></el-input>
      </el-form-item>
      <el-form-item label="APPKEY" prop="appKey">
        <el-input size="mini"  v-model.trim="weiboDetailFrom.appKey" auto-complete="off" :disabled="true"></el-input>
      </el-form-item>

      <el-form-item label="是否启用日程" prop="scheduleEnable" v-show="configType === 'config'">
        <el-radio-group v-model.trim="weiboDetailFrom.scheduleEnable">
          <el-radio :label="true">启用</el-radio>
          <el-radio :label="false">不启用</el-radio>
        </el-radio-group>
      </el-form-item>
      <p class="remark" style="padding-left: 0px">温馨提示：请确保您已配置相关日程，否则将无法正常启用。您可以到“日程管理”下面配置相应日程。</p>
      <el-form-item v-show="!weiboDetailFrom.scheduleEnable" :label="$t('config.channel.msgToPeer2')" prop="to_peer">
        <el-select size="mini" v-model="weiboDetailFrom.to_peer" :placeholder="$t('public.pleasePick')" class="select">
          <el-option
                  v-for="item in peerOptions"
                  :key="item._id"
                  :label="item.DisplayName"
                  :value="item.Exten">
          </el-option>
        </el-select>
      </el-form-item>
      <el-form-item v-show="!weiboDetailFrom.scheduleEnable" :label="$t('config.channel.isUseRobt2')" prop="robot">
        <el-select size="mini" v-model="weiboDetailFrom.robot" :placeholder="$t('public.pleasePick')" class="select" @visible-change="robotSelectShow">
          <el-option value="">{{$t('public.pleasePick')}}</el-option>
          <el-option
                  v-for="item in allrobotOptions"
                  :key="item._id"
                  :label="item.robot_name_new"
                  :disabled="item.disabled"
                  :value="item._id">
          </el-option>
        </el-select>
      </el-form-item>
      <el-form-item v-show="!weiboDetailFrom.scheduleEnable && aiRobots.length > 0"  label="机器人辅助座席" prop="robotAssistId">
        <el-select size="mini" v-model.trim="weiboDetailFrom.robotAssistId" :placeholder="$t('public.pleasePick')" class="select" @visible-change="robotSelectShow">
          <el-option value="">{{$t('public.pleasePick')}}</el-option>
          <el-option
                  v-for="item in aiRobots"
                  :key="item._id"
                  :label="item.robot_name_new"
                  :disabled="item.disabled"
                  :value="item._id">
          </el-option>
        </el-select>
      </el-form-item>
      <el-form-item label="是否开启触发词命中转人工" prop="scheduleEnable" v-show="configType === 'config'">
        <el-radio-group v-model.trim="weiboDetailFrom.openTriggerWord">
          <el-radio :label="true">是</el-radio>
          <el-radio :label="false">否</el-radio>
        </el-radio-group>
        <question-tooltip
                :tipContent="'开启后，访客发送的消息匹配到转人工触发词后，将自动转接人工客服，提高接待效率'"
                class="weiboTootip">
        </question-tooltip>
      </el-form-item>
      <el-form-item :label="$t('config.channel.userPeopleWord2')" prop="convert_words">
        <question-tooltip
                :tipContent="'1，可设置多个，多个触发词用英文逗号隔开。<br/>2，需要全部命中触发词，如：触发词为“转人工”则必须输入“转人工”才能转入人工。'"
                class="weiboTootip">
        </question-tooltip>
        <el-input size="mini" v-model.trim="weiboDetailFrom.convert_words"></el-input>
      </el-form-item>
      <el-form-item v-show="!weiboDetailFrom.scheduleEnable" :label="$t('config.channel.sendWelcomeMsg2')" prop="welcomePushTime">
        <el-radio-group v-model="weiboDetailFrom.welcomePushTime" @change="pushTimeChange">
          <el-radio class="radio" label="access">{{$t('config.channel.enterSystem')}}</el-radio>
          <el-radio class="radio welcome-radio" label="claim">{{$t('config.channel.collectSeats')}}</el-radio>
        </el-radio-group>
      </el-form-item>
      <el-form-item v-show="!weiboDetailFrom.scheduleEnable" :label="$t('config.channel.welcomeMsg2')" prop="welcome_msg">
        <span class="remark">点击“+”即可将占位符填充到您输入内容的后方。</span>
        <question-tooltip
                class="wechatTootip"
                :direction="'bottom'"
                :tipContent="'占位符是指系统自动获取的客户和座席相关信息，可用于配制组合欢迎语内容，如：亲爱的{nickName}您好，其中{nickName}为获取到的访客名称。</br>注意：获取的信息为您接入网站代码时定义的相关信息，如需使用占位符，请先在接入网站时接入相关代码。座席工号和座席名称只有在座席领取后推送欢迎语才会有效'">
        </question-tooltip>
        <div class="placeholder_box">
          <dl v-for="place in placeholderArr" @click="addPlaceholder(place.data)" :title="place.content">
            {{place.content}}
            <i class="iconfont icon-zhankai"></i>
          </dl>
        </div>
        <el-input size="mini" type="textarea" v-model="weiboDetailFrom.welcome_msg"></el-input>
      </el-form-item>
      <el-form-item :label="$t('config.channel.isUseSatisfaction2')" prop="webchat_csr">
        <el-radio class="radio" v-model="weiboDetailFrom.webchat_csr" :label="false">{{$t('config.channel.notEnabled')}}</el-radio>
        <el-radio class="radio statis-radio" v-model="weiboDetailFrom.webchat_csr" :label="true">{{$t('config.channel.enabled')}}</el-radio>
      </el-form-item>
    </el-form>
    <div class="btn-group">
      <el-button type="primary" class="primary_btn" @click.stop="save()">{{$t('public.save')}}</el-button>
    </div>
  </div>
</template>
<script>
  import questionTooltip from '@/components/ui-modules/questionToolTip/QuestionToolTip.vue'
  import { deepClone } from '@utils/m7Utils.js'
  
  export default {
    name: 'WeiboDetail',
    data () {
      let checkWeiboId = (rule, value, callback) => {
        if (!value) {
          return callback(new Error('必填'))
        }
        setTimeout(() => {
          if (!/^[1-9]\d*$/.test(value)) {
            callback(new Error(this.$t('config.channel.weiboIdMustNumber')))
          } else {
            callback()
          }
        }, 100)
      }
      return {
        rules: {
          name: [
            { required: true, message: '必填', trigger: 'blur' }
          ],
          weiboId: [
            { required: true, validator: checkWeiboId, trigger: 'blur' }
          ],
          access_token: [
            { required: true, message: '必填', trigger: 'blur' }
          ]
        },
        weiboDetailFrom: {},
        aiRobots: [],
        allrobotOptions: [],
        placeholderArr: [
          {
            content: this.$t('configLazyLoad.channel.nickName'),
            data: 'nickName'
          }
        ]
      }
    },
    components: {
      questionTooltip
    },
    computed: {
      configType () {
        let paths = this.$route.path.split('/')
        return paths[2]
      }
    },
    props: {
      weiboDetail: {type: Object, default: {}},
      peerOptions: Array
    },
    watch: {
      weiboDetail (cur) { // 解决点击修改没有重新渲染的问题
        this.weiboDetailFrom = deepClone(cur)
        if (this.weiboDetailFrom.openTriggerWord === undefined) {
          this.$set(this.weiboDetailFrom, 'openTriggerWord', true)
        }
        this.pushTimeChange(this.weiboDetailFrom.welcomePushTime)
      }
    },
    methods: {
      robotSelectShow (show) {
        if (show) {
          this.$store.dispatch('queryM7AIRobot', {}).then((res2) => {
            if (res2 && res2.success && res2.data && res2.data.length > 0) {
              let aiRobot = res2.data
              let allRobot = this.allrobotOptions
              aiRobot.forEach((item1) => {
                item1._id = item1.Id
                item1.robot_name_new = item1.Nick
                let exist = allRobot.findIndex((all) => {
                  return all.Id === item1.Id
                })
                if (exist === undefined) {
                  allRobot.push(item1)
                } else {
                  allRobot.splice(exist, 1, item1)
                }
              })
              this.aiRobots = aiRobot
              this.allrobotOptions = allRobot
            }
          })
        }
      },
      cancle () {
        this.$emit('cancle')
      },
      save () {
        this.$refs.weiboDetailFrom.validate((valid) => {
          if (valid) {
            let data = this.weiboDetailFrom
            data._id = data.weiboId
            data.accessId = data.weiboId
            if (!data.scheduleEnable) {
              if (!data.to_peer) {
                this.$message.error('请选择技能组')
                return
              }
              if (!data.robot) {
                data.robotType = ''
              } else {
                this.allrobotOptions.forEach((item) => {
                  if (item._id === data.robot) {
                    if (item.Nick) {
                      data.robotType = item.robotType
                    } else {
                      data.robotType = item.robot_type_new
                    }
                  }
                })
              }
//          机器人辅助座席，增加assistRobotType参数
              this.aiRobots.map((item) => {
                if (data.robotAssistId === item._id) {
                  if (data.robotAssistId !== '') {
                    this.$set(data, 'assistRobotType', item.robotType)
                  } else {
                    this.$set(data, 'assistRobotType', '')
                  }
                }
              })
            }
            this.$store.dispatch('saveBindWeiboDetail', data).then((resp) => { // 获取url 和appKey
              if (resp.success) {
                this.$message.success(this.$t('config.channel.saveWeiboSuccess'))
                this.$emit('cancle') // 保存成功之后要关闭详细信息页
                this.$emit('refresh') // 保存成功之后刷新列表
              } else {
                this.$message.error(resp.message)
              }
            })
          } else {
            return false
          }
        })
      },
      addPlaceholder (msg) {
        this.weiboDetailFrom.welcome_msg += '{' + msg + '}'
      },
      pushTimeChange (data) {
        if (data === 'access') {
          this.placeholderArr = [
            {
              content: '访客名称：nickName',
              data: 'nickName'
            }
          ]
          let str = deepClone(this.weiboDetailFrom.welcome_msg)
          str = str.replace(/\{agent\}/g, '')
          str = str.replace(/\{agentName\}/g, '')
          this.weiboDetailFrom.welcome_msg = str
        } else if (data === 'claim') {
          this.placeholderArr = [
            {
              content: this.$t('configLazyLoad.channel.nickName'),
              data: 'nickName'
            }, {
              content: this.$t('configLazyLoad.channel.agent'),
              data: 'agent'
            }, {
              content: this.$t('configLazyLoad.channel.agentName'),
              data: 'agentName'
            }, {
              content: this.$t('configLazyLoad.channel.agentNickName'),
              data: 'agentNickName'
            }, {
              content: this.$t('configLazyLoad.channel.agentPhone'),
              data: 'agentPhone'
            }
          ]
        }
      }
    },
    mounted () {
      this.$store.dispatch('getCache', { type: 'robotConfig' }).then(req => {
        let robotConfig = this.$getCache('robotConfig')
        this.allrobotOptions = robotConfig || []
        this.$store.dispatch('queryM7AIRobot', {}).then((res2) => {
          if (res2 && res2.success && res2.data && res2.data.length > 0) {
            let aiRobot = res2.data
            aiRobot.forEach((item1) => {
              item1._id = item1.Id
              item1.robot_name_new = item1.Nick
            })
            this.aiRobots = aiRobot
            let configArr = []
            robotConfig.forEach((config) => {
              if (config.robot_type !== 'didi') {
                configArr.push(config)
              }
            })
            this.allrobotOptions = configArr.concat(this.aiRobots)
          }
        })
      })
    },
    beforeMount () {
      this.weiboDetailFrom = deepClone(this.weiboDetail) || {}
      this.pushTimeChange(this.weiboDetailFrom.welcomePushTime)
      if (!this.weiboDetailFrom.scheduleEnable) {
        this.$set(this.weiboDetailFrom, 'scheduleEnable', false)
      }
      if (!this.weiboDetailFrom.robotAssistId) {
        this.$set(this.weiboDetailFrom, 'robotAssistId', '')
      }
      if (this.weiboDetailFrom.openTriggerWord === undefined) {
        this.$set(this.weiboDetailFrom, 'openTriggerWord', true)
      }
      // 判断小七是否回显
      if (this.$store.state.isM7RobotOpen === false) {
        if (this.weiboDetailFrom.robot === '5825a500dfe52d5edc6e36c9') {
          this.weiboDetailFrom.robot = ''
        }
      }
    }
  }
</script>
<style lang="stylus" scoped>
  @import "../../../../../assets/common.styl"
  .detail-wrap
    padding-top 20px
    width 440px
    margin 0 auto
    .select
      width 100%
    .btn-group
      margin 20px 0 30px
      text-align center
    .weiboTootip
      position absolute
      right -2em
  .remark
    color #3b5998
    font-size 12px
    .tip
      cursor pointer
      display inline-block
      height 16px
      width 16px
      border 1px solid $c-main
      text-align center
      line-height 16px
      border-radius 50%
      margin-left 2px
      .iconfont
        font-size 10px
        color $c-main
  .placeholder_box
    margin-top 10px
    font-size 12px
    line-height:16px
    dl
      border 1px solid $c-main
      color $c-main
      border-radius 6px
      display inline-block
      padding 4px
      margin 0 10px 10px 0
      cursor pointer
    .iconfont
      font-size 12px
</style>
